package com.chart.web.controller.chart;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chart.chart.domian.ChartConfigsUser;
import com.chart.chart.domian.req.UListReq;
import com.chart.chart.domian.vo.ChartColorsVO;
import com.chart.chart.domian.vo.ChartConfigsUserVo;
import com.chart.chart.domian.vo.UserCoinLogVo;
import com.chart.chart.service.IChartConfigsUserService;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.entity.UserCoinLog;
import com.chart.common.utils.SecurityUtils;
import com.chart.common.utils.StringUtils;
import com.chart.common.utils.poi.ExcelUtil;
import com.chart.system.service.ISysUserService;
import com.chart.system.service.IUserCoinLogsService;
import com.chart.system.service.impl.SysUserServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * 每天登录送币4
 * 完善信息送币10一个用户只能送一次
 * 转发送币2 一天限制五次
 */
@RestController
@RequestMapping("/user/coinLog")
public class UserCoinLogController {
    private static final Logger log = LoggerFactory.getLogger(UserCoinLogController.class);
    @Autowired
    private IUserCoinLogsService userCoinLogsService;

    @Autowired
    private IChartConfigsUserService chartConfigsUserService;


    /**
     * 用户金币增加操作接口
     *
     * @param userId 用户ID
     * @param action 操作类型 (login: 每天登录送币, completeInfo: 完善信息送币, share: 转发送币)
     * @return 操作结果
     */
    @PostMapping("/operate")
    public AjaxResult operate(@RequestParam(required = false) Long userId, @RequestParam String action) {

        // 参数校验
        if (userId == null && SecurityUtils.getUserId() == null) {
            log.warn("用户ID为空且无法从安全上下文中获取");
            return AjaxResult.error("用户ID不能为空");
        }
        if (userId == null) {
            userId = SecurityUtils.getUserId();
            if (userId == null) {
                log.error("未从SecurityUtils.getUserId()获取用户id：{}", userId);
            }
        }

        //绑定公众号 10
        int coinsAdded = 0;
        switch (action) {
            case "login":
                coinsAdded = userCoinLogsService.addLoginCoins(userId);
                break;
            case "completeInfo":
                coinsAdded = userCoinLogsService.addInfoCompletionCoins(userId);
                break;
            case "share":
                coinsAdded = userCoinLogsService.addShareCoins(userId);
                break;
            case "bind":
                coinsAdded = userCoinLogsService.addweChatPublicnumber(userId);
                break;
            default:
                log.warn("未知的操作类型：{}", action);
                return AjaxResult.error("无效的操作类型");
        }
        Integer totalCoins = userCoinLogsService.getTotalCoinsByUserId(userId);
        // 检查totalCoins是否为null
        if (totalCoins == null) {
            log.warn("未能获取用户{}的总积分", userId);
            return AjaxResult.error("未能获取用户的总积分");
        }
        // 根据totalCoins的值进行进一步的条件判断
        if (totalCoins > 0) {
            log.info("用户{}的总积分为{}", userId, totalCoins);
        } else if (totalCoins <= 0) {
            log.info("用户{}的总积分小于或等于0", userId);
        }
        // 构建返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("coinsAdded", coinsAdded);
        data.put("totalCoins", totalCoins);
        return AjaxResult.success("操作成功", data);
    }


    /**
     * 转发剩余次数
     *
     * @return
     */
    @GetMapping("residue/time")
    public AjaxResult residueTime() {
        Long userId = SecurityUtils.getUserId();
        int i = userCoinLogsService.residueTime(userId);
        return AjaxResult.success(i);
    }


    /**
     * 扣除AI接口金币
     *
     * @param userId 用户ID
     * @param action 扣除动作
     * @return 扣除结果
     */
    @PostMapping("/deductAiCoins")
    public AjaxResult deductAiCoins(@RequestParam(required = false) Long userId, @RequestParam String action) {

        if (userId == null) {
            userId = SecurityUtils.getUserId();
        }
        int deductedCoins = 0;
        switch (action) {
            case "deductAi":
                deductedCoins = userCoinLogsService.deductAiCoins(userId);
                break;
            case "casePool":
                deductedCoins = userCoinLogsService.deductCasePool(userId);
                break;
            case "aiColor":
                deductedCoins = userCoinLogsService.deductAiColor(userId);
                break;
            default:
                return AjaxResult.error("无效的扣除动作");
        }
        if (deductedCoins > 0) {
            Integer totalCoins = userCoinLogsService.getTotalCoinsByUserId(userId);
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("deductAiCoins", deductedCoins);
            data.put("totalCoins", totalCoins);
            return AjaxResult.success("操作成功", data);
        } else {
            return AjaxResult.error("扣除失败，金币不足");
        }
    }


    /**
     * 扣除AI接口金币
     *
     * @param
     * @param
     * @return 扣除结果
     */
    @PostMapping("/deductCoins")
    public AjaxResult deductAiCoins(Integer coins, String type) {
        Long userId = SecurityUtils.getUserId();
        Integer totalCoins = userCoinLogsService.getTotalCoinsByUserId(userId);
        if (coins == 0) {
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("deductAiCoins", coins);
            data.put("totalCoins", totalCoins);
            data.put("deductStatus", 0);
            return AjaxResult.success("操作成功", data);
        }
        if (totalCoins - coins < 0) {
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("deductAiCoins", 0);
            data.put("totalCoins", totalCoins);
            data.put("deductStatus", 1);
            return AjaxResult.success("金币不足", data);
        } else {
            // 扣除金币
            UserCoinLog log = new UserCoinLog();
            log.setUserId(userId);
            log.setAction(type);
            log.setCoins(-coins); // 扣除金币数，使用负值表示扣除
            log.setCreatedAt(LocalDateTime.now());
            userCoinLogsService.save(log);


            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("deductAiCoins", coins);
            data.put("totalCoins", totalCoins);
            data.put("deductStatus", 0);
            return AjaxResult.success("操作成功", data);
        }

    }

    /**
     * 用户扣币行为查询
     *
     * @param
     * @return
     */

    @PostMapping("/queryAction")
    public AjaxResult queryAction(@RequestBody UListReq req) {
        List<UserCoinLog> logs = userCoinLogsService.queryAction(req);


        for (UserCoinLog log : logs) {
            String action = log.getAction();
            switch (action) {
                case "aiDeduct":
                    log.setActionInfo(" ai制图导出");
                    break;
                case "baseDeduct":
                    log.setActionInfo("基础制图-高清导出");
                    break;
                case "expertDeduct":
                    log.setActionInfo("专家图例（只有高清选项）导出");
                    break;
                case "fileDeduct":
                    log.setActionInfo("可保存文件数扩容");
                    break;
                case "aiColorDeduct":
                    log.setActionInfo("AI问色");
                    break;
            }
        }
        return AjaxResult.success(logs);
    }









    /**
     * 导出excel
     *
     * @param req
     * @return
     * @throws IOException
     */
    @PostMapping("/queryAction/exportExcel")
    public ResponseEntity<byte[]> queryActions(@RequestBody UListReq req) throws IOException {
        List<UserCoinLog> logs = userCoinLogsService.queryAction(req);
        // Add the action info based on the action type
        for (UserCoinLog log : logs) {
            String action = log.getAction();
            switch (action) {
                case "aiDeduct":
                    log.setActionInfo(" ai制图导出");
                    break;
                case "baseDeduct":
                    log.setActionInfo("基础制图-高清导出");
                    break;
                case "expertDeduct":
                    log.setActionInfo("专家图例（只有高清选项）导出");
                    break;
                case "fileDeduct":
                    log.setActionInfo("可保存文件数扩容");
                    break;
                case "aiColorDeduct":
                    log.setActionInfo("AI问色");
                    break;
            }
        }

        // Create an Excel file
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("User Coin Logs");
        // Create header row
        Row headerRow = sheet.createRow(0);
        String[] headers = {"手机号", "订单详情", "订单时间", "智点数量"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // DateTimeFormatter to format date
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // Fill data rows
        int rowNum = 1;
        for (UserCoinLog log : logs) {
            Row row = sheet.createRow(rowNum++);
            // Assuming createdAt is of type LocalDateTime or ZonedDateTime
            String formattedDate = log.getCreatedAt().format(dateFormatter);
            row.createCell(0).setCellValue(log.getPhonenumber());
            row.createCell(1).setCellValue(log.getActionInfo());
            row.createCell(2).setCellValue(formattedDate);
            row.createCell(3).setCellValue(log.getCoins());
            // Updated index to 2
            // Updated index to 3
        }


        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();


        HttpHeaders headersResponse = new HttpHeaders();
        headersResponse.add("Content-Disposition", "attachment; filename=user_coin_logs.xlsx");
        return new ResponseEntity<>(outputStream.toByteArray(), headersResponse, HttpStatus.OK);
    }


    @PostMapping("/totalCoins")
    public AjaxResult getTotalCoins(@RequestParam(required = false) Long userId) {

        if (userId == null) {
            userId = SecurityUtils.getUserId();
        }
        Integer totalCoins = userCoinLogsService.getTotalCoinsByUserId(userId);

        return AjaxResult.success(totalCoins);
    }


    @PostMapping("/saveBehavior")
    public AjaxResult saveBehavior(@RequestParam(required = false) Long userId, @RequestParam String behavior) {

        if (userId == null) {
            userId = SecurityUtils.getUserId();
        }

        switch (behavior) {
            case "no":
                userCoinLogsService.saveBehaviorNo(userId);
                break;
            case "yes":
                userCoinLogsService.saveBehaviorYes(userId);
                break;
            case "close":
                userCoinLogsService.saveBehaviorClose(userId);
                break;
            default:
                return AjaxResult.error("无效的操作类型");
        }

        Integer totalNo = userCoinLogsService.getTotalNoByUserId(userId);
        Integer totalYes = userCoinLogsService.getTotalYesByUserId(userId);
        Integer totalClose = userCoinLogsService.getTotalCloseByUserId(userId);
        // 构建返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("totalNo", totalNo);
        data.put("totalYes", totalYes);
        data.put("totalClose", totalClose);
        return AjaxResult.success("操作成功", data);
    }


    /**
     * 使用说明点击的PV、UV
     *
     * @return
     */
    @PostMapping("/operationPVUv")
    public AjaxResult logActivity() {
        return userCoinLogsService.logActivity();
    }

    /**
     * 使用说明点击的PV、UV查询
     *
     * @return
     */
    @GetMapping("/operationPvUvTotal")
    public AjaxResult getActivitySummary() {
        return userCoinLogsService.getActivitySummary();
    }

    /**
     * 导出使用说明点击的PV、UV
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/exportActivitySummaryExcel")
    public void exportActivitySummary(HttpServletResponse response) throws IOException {
        // 获取数据
        AjaxResult summaryResult = userCoinLogsService.getActivitySummary();
        HashMap<String, Object> summary = (HashMap<String, Object>) summaryResult.get("data");

        // 设置响应头
        String fileName = "使用说明.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" +
                URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()));

        try (Workbook workbook = new XSSFWorkbook();
             OutputStream outputStream = response.getOutputStream()) {

            // 创建工作表
            Sheet sheet = workbook.createSheet("使用说明");

            // 创建标题行
            String[] columns = {"使用说明", "数量"};
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < columns.length; i++) {
                headerRow.createCell(i).setCellValue(columns[i]);
            }

            // 填充数据
            Row dataRow = sheet.createRow(1);
            dataRow.createCell(0).setCellValue("UV");
            dataRow.createCell(1).setCellValue(summary.get("uv") != null ? summary.get("uv").toString() : "0");

            dataRow = sheet.createRow(2);
            dataRow.createCell(0).setCellValue("PV");
            dataRow.createCell(1).setCellValue(summary.get("pv") != null ? summary.get("pv").toString() : "0");

            // 写入Excel文件
            workbook.write(outputStream);
            outputStream.flush(); // 确保所有数据写入输出流
        } catch (IOException e) {
            e.printStackTrace(); // 处理异常
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 设置错误状态码
        }
    }


    /**
     * 当日智点用尽时，询问用户是否愿意付费
     * 分析用户付费意愿
     * 插入接口
     * 不愿意支付 UNWILLINGTOPAY
     * 愿意支付 BEWILLINGTOPAY"
     *
     * @return
     */
    @PostMapping("analyzeUsersPay")
    public AjaxResult analyzeUsersPay(String action) {
        userCoinLogsService.saveAnalyzeUsersPay(action);
        return AjaxResult.success();
    }

    @GetMapping("queryUsersPay")
    public AjaxResult queryUsersPay() {
        // 创建查询条件
        LambdaQueryWrapper<UserCoinLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserCoinLog::getUserId, SecurityUtils.getUserId());
        // 统计 action 等于 UNWILLINGTOPAY 的数量
        queryWrapper.eq(UserCoinLog::getAction, "UNWILLINGTOPAY");
        int unwillingToPayCount = userCoinLogsService.count(queryWrapper);

        LambdaQueryWrapper<UserCoinLog> lqw = new LambdaQueryWrapper<>();
        // 统计 action 等于 BEWILLINGTOPAY 的数量
        lqw.eq(UserCoinLog::getAction, "BEWILLINGTOPAY");
        int willingToPayCount = userCoinLogsService.count(lqw);
        // 创建返回结果
        Map<String, Integer> result = new HashMap<>();
        result.put("UNWILLINGTOPAY", unwillingToPayCount);
        result.put("BEWILLINGTOPAY", willingToPayCount);
        return AjaxResult.success(result);
    }


    /**
     * 插入补充信息
     *
     * @return
     */
    @PostMapping("supplement")
    public AjaxResult supplement() {
        Integer supplement = 1; //代表已经补充信息
        Long userId = SecurityUtils.getUserId();
        UserCoinLog userCoinLog = new UserCoinLog();
        userCoinLog.setSupplement(supplement);
        userCoinLog.setUserId(userId);

        userCoinLogsService.save(userCoinLog);
        return AjaxResult.success();
    }


    /**
     * 补充信息查询
     *
     * @return
     */
    @GetMapping("querySupplement")
    public AjaxResult querySupplement() {
        LambdaQueryWrapper<UserCoinLog> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserCoinLog::getSupplement, 1);
        lqw.eq(UserCoinLog::getUserId, SecurityUtils.getUserId());

        int added = userCoinLogsService.count(lqw);

        LambdaQueryWrapper<UserCoinLog> qw = new LambdaQueryWrapper<>();
        qw.eq(UserCoinLog::getSupplement, 0);
        qw.eq(UserCoinLog::getUserId, SecurityUtils.getUserId());
        int notAdded = userCoinLogsService.count(qw);

        HashMap<String, Integer> map = new HashMap<>();
        map.put("added", added);
        map.put("notAdded", notAdded);
        return AjaxResult.success(map);
    }


    /**
     * 统计转发地方次数PV UV
     */
    @GetMapping("sherePvUv")
    public AjaxResult sherePv() {
        String action = "SHARE";
        List<UserCoinLog> list = userCoinLogsService.getUserCoinLogsByAction(action);
        Integer shereUv = userCoinLogsService.shereUv();
        int sherePv = list.size();

        HashMap<Object, Object> map = new HashMap<>();
        map.put("sherePv", sherePv);
        map.put("shereUv", shereUv);
        return AjaxResult.success(map);
    }


    /**
     * 我的生成插入操作
     */
    @PostMapping("saveSelfProduce")
    public AjaxResult saveSelfProduce() {
        userCoinLogsService.saveSelfProduce();
        return AjaxResult.success();
    }

    /**
     * 我的生成查询
     *
     * @return
     */
    @GetMapping("querySelfProduce")
    public AjaxResult querySelfProduce() {
        Integer size = userCoinLogsService.querySelfProduce();
        return AjaxResult.success(size);
    }


    /**
     * 我的生成AI插入操作
     */
    @PostMapping("saveAiSelfProduce")
    public AjaxResult saveAiSelfProduce() {
        userCoinLogsService.saveAiSelfProduce();
        return AjaxResult.success();
    }

    /**
     * AI保存
     *
     * @return
     */

    @PostMapping("saveAiSave")
    public AjaxResult saveAiSave() {
        userCoinLogsService.saveAiSave();
        return AjaxResult.success();
    }


    /**
     * 我的生成AI查询
     */
    @GetMapping("queryAiSelfProduce")
    public AjaxResult queryAiSelfProduce() {
        Integer size = userCoinLogsService.queryAiSelfProduce();
        return AjaxResult.success(size);
    }

    /**
     * AI查询
     *
     * @return
     */
    @GetMapping("queryAiSave")
    public AjaxResult queryAiSave() {
        Integer size = userCoinLogsService.queryAiSave();
        return AjaxResult.success(size);
    }


    /**
     * 专家我的生成导入
     */
    @PostMapping("expertSave")
    public AjaxResult expertSave(Long configsUserId) {
        userCoinLogsService.expertSave(configsUserId);
        return AjaxResult.success();
    }

    /**
     * 专家图例导出
     */
    @PostMapping("expertExport")
    public AjaxResult expertExport(Long configsUserId) {
        userCoinLogsService.expertSaveExport(configsUserId);
        return AjaxResult.success();
    }


    /**
     * 专家图例保存导出 查询UV
     */
    @GetMapping("queryExpertSaveUv")
    public AjaxResult queryExpertSaveUv() {
        Integer saveUv = userCoinLogsService.queryExpertSaveUv();
        Integer exportUV = userCoinLogsService.queryExpertSaveUvs();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("saveUv", saveUv);
        map.put("exportUV", exportUV);
        return AjaxResult.success(map);
    }


    /**
     * 专家图例保存导出 查询UV
     *
     * @return
     */
    @GetMapping("queryExpertSaveExportUV")
    public AjaxResult queryExpertSaveExportUV() {
        //UV
        List<Map<String, Object>> userCoinLogUVs = userCoinLogsService.queryExpertSaveExportUV();
        return AjaxResult.success(userCoinLogUVs);

    }


    /**
     * 用户增加席位数量
     *
     * @return
     */

    @GetMapping("/saveSeatCount")
    public AjaxResult saveSeatCount(int seatCount) {
        Long userId = SecurityUtils.getUserId();
        Integer totalCoins = userCoinLogsService.getTotalCoinsByUserId(userId);
        if (totalCoins < 10) {
            return AjaxResult.success("智点不足 扣除失败");
        } else {
            UserCoinLog userCoinLog = new UserCoinLog();
            userCoinLog.setUserId(userId);
            userCoinLog.setSeatCount(seatCount);
            userCoinLog.setBehavior("SEATCOUNT");
            userCoinLogsService.save(userCoinLog);
            return AjaxResult.success(seatCount);
        }


    }

    /**
     * 用户查询席位数量
     * 已经使用席位
     * 剩余席位
     *
     * @param
     * @return
     */
    @GetMapping("/querySeatCount")
    public AjaxResult querySeatCount() {
        int seatCountNumber = userCoinLogsService.querySeatCount();//总席位数量
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<ChartConfigsUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ChartConfigsUser::getUserId, userId);
        List<ChartConfigsUser> chartConfigsUsers = chartConfigsUserService.list(lqw);
        int size = chartConfigsUsers.size(); //已经使用的席位
        HashMap<Object, Object> map = new HashMap<>();
        map.put("seatCountNumber", seatCountNumber);
        map.put("alreadySeatCount", size);
        return AjaxResult.success(map);
    }


    /**
     * 删除席位
     *
     * @return
     */
    @PostMapping("delSeatCount")
    public AjaxResult delSeatCount(Integer seatCount) {
        Long userId = SecurityUtils.getUserId();
        // 扣除金币
        UserCoinLog log = new UserCoinLog();
        log.setUserId(userId);
        log.setAction("");
        log.setCoins(-seatCount); // 扣除金币数，使用负值表示扣除
        log.setCreatedAt(LocalDateTime.now());
        userCoinLogsService.save(log);

        return AjaxResult.success();
    }


    /**
     * 每登录一次调用一次这个方法
     *
     * @return
     */
    @PostMapping("login/log")
    public AjaxResult loginLog() {
        Long userId = SecurityUtils.getUserId();
        UserCoinLog log = new UserCoinLog();
        log.setUserId(userId);
        log.setAction("LOGINLOG");
        log.setCoins(0);
        log.setCreatedAt(LocalDateTime.now());

        // 使用 Instant 获取当前时间并转换
        Instant nowInstant = Instant.now();
        LocalDateTime now = LocalDateTime.ofInstant(nowInstant, ZoneId.systemDefault());
        Date nowAsDate = Date.from(nowInstant);

        log.setCreateTime(nowAsDate);

        userCoinLogsService.save(log);
        return AjaxResult.success();
    }

    /**
     * 登录记录日志查询loginLog
     *
     * @return
     */
    @GetMapping("query/loginLog")
    public AjaxResult queryLoginLog() {

        // 获取当天的开始时间（最小值）
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        // 获取当天的结束时间（最大值）
        LocalDateTime endOfDay = LocalDate.now().atTime(23, 59, 59, 999999999);

        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<UserCoinLog> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserCoinLog::getUserId, userId);
        lqw.eq(UserCoinLog::getAction, "LOGINLOG");
        lqw.ge(UserCoinLog::getCreatedAt, startOfDay); //大于等于
        lqw.le(UserCoinLog::getCreatedAt, endOfDay); //小于等于
        List<UserCoinLog> list = userCoinLogsService.list(lqw);
        // 统计登录次数
        long loginCount = list.size();
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("dailyloginCount", loginCount);
        return AjaxResult.success(result);
    }


    /**
     * 专家图例的PU
     *
     * @return
     */
//    @GetMapping("queryExpertSaveExportPU")
//    public  Map<String, Object> queryExpertSaveExportStats(@RequestBody UListReq req) {
//        Map<String, Object> result = userCoinLogsService.queryExpertSaveExportStats(req);
//        return result;
//    }
    // @GetMapping("queryExpertSaveExportPU")
    public Map<String, Object> queryExpertSaveExportStats() {
        try {
            return userCoinLogsService.queryExpertSaveExportStats();
        } catch (ParseException e) {
            e.printStackTrace();
            // Handle exception or return an error response
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("msg", "操作失败");
            errorResponse.put("code", 500);
            errorResponse.put("data", null);
            return errorResponse;
        }
    }


    // @PostMapping("queryExpertSaveExportPU")
    public AjaxResult queryPU(@RequestBody UListReq req) {
        List<UserCoinLogVo> chartDataList = userCoinLogsService.getChartData(req);
        return AjaxResult.success(chartDataList);
    }

    /**
     * 专家图例导出
     */
    @PostMapping("queryExpertSaveExportPU")
    public AjaxResult queryExpertSaveExports(@RequestBody UListReq req) {
        List<UserCoinLogVo> chartDataList = userCoinLogsService.queryExpertSaveExports(req);
        return AjaxResult.success(chartDataList);
    }


    @PostMapping("queryExpertSaveExportExcel")
    public void exportExcel(@RequestBody UListReq req, HttpServletResponse response) throws IOException {
        // 设置响应头，通知浏览器下载文件
        String fileName = "UserOperationLogs.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" +
                URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()));
        String startDate = req.getStartTime();
        String endDate = req.getEndTime();
        // 固定的开始和结束时间
//        String startDate = "2024-01-01"; // 替换为实际的开始日期
//        String endDate = "2024-12-31";   // 替换为实际的结束日期
        Map<String, Object> params = new HashMap<>();
        params.put("startDate", startDate);
        params.put("endDate", endDate);

        // 根据参数获取数据
        List<UserCoinLogVo> chartDataList = userCoinLogsService.queryExpertSaveExports(req);
        if (chartDataList == null || chartDataList.isEmpty()) {
            // 处理列表为空或null的情况
            log.warn("查询结果为空或未找到数据");

        }

        try (Workbook workbook = new XSSFWorkbook();
             OutputStream outputStream = response.getOutputStream()) {

            // 创建工作表
            Sheet sheet = workbook.createSheet("用户操作日志");

            // 创建标题行
            String[] columns = {
                    "图表配置名称", "保存PV",
                    "导出PV", "保存UV", "导出UV"
            };
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < columns.length; i++) {
                headerRow.createCell(i).setCellValue(columns[i]);
            }

            // 填充数据
            int rowNum = 1;
            for (UserCoinLogVo data : chartDataList) {
                Row excelRow = sheet.createRow(rowNum++);
                excelRow.createCell(0).setCellValue(data.getChartName() != null ? data.getChartName() : "");
                excelRow.createCell(1).setCellValue(data.getSave() != null ? data.getSave() : 0);
                excelRow.createCell(2).setCellValue(data.getExport() != null ? data.getExport() : 0);
                excelRow.createCell(3).setCellValue(data.getSaveUv() != null ? data.getSaveUv() : 0);
                excelRow.createCell(4).setCellValue(data.getExportUv() != null ? data.getExportUv() : 0);
            }

            // 写入Excel文件
            workbook.write(outputStream);
            outputStream.flush(); // 确保所有数据写入输出流
        } catch (IOException e) {
            e.printStackTrace(); // 处理异常
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 设置错误状态码
        }
    }


    /**
     * ai问色PV查询
     */

    @PostMapping("queryAiColorPU")
    public AjaxResult queryAiColorPU(@RequestBody UListReq req) {
        List<ChartColorsVO> colorsVOList=  userCoinLogsService.queryAiColorPV(req);
        return AjaxResult.success(colorsVOList);
    }


    /**
     *  ai问色PV查询导出
     * @param response
     * @param req
     */

    @ApiOperation("导出图表配置计数")
    @PostMapping("queryAiColorPUExport")
    public void chartConfigCountExports(HttpServletResponse response,@RequestBody UListReq req) {
        List<ChartColorsVO> colorsVOList=  userCoinLogsService.queryAiColorPV(req);
        ExcelUtil<ChartColorsVO> util = new ExcelUtil<>(ChartColorsVO.class);
        util.exportExcel(response, colorsVOList, "用户保存管理");
    }



    @ApiOperation("导出图表配置计数")
    @PostMapping("/export/chartConfigCountExport")
    public void chartConfigCountExport(HttpServletResponse response, @RequestBody UListReq req) {
        List<ChartConfigsUserVo> chartConfigsUsers = chartConfigsUserService.querychartConfigCount(req);

        ExcelUtil<ChartConfigsUserVo> util = new ExcelUtil<>(ChartConfigsUserVo.class);

        util.exportExcel(response, chartConfigsUsers, "用户保存管理");
    }




}











